import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.*;

public class CustomerManageFrame extends JFrame {
    private JTable customerTable;
    private DefaultTableModel tableModel;

    public CustomerManageFrame() {
        setTitle("客户管理");
        setSize(800, 500);
        setLocationRelativeTo(null);

        // 表格模型
        tableModel = new DefaultTableModel();
        tableModel.addColumn("客户编号");
        tableModel.addColumn("名称");
        tableModel.addColumn("地址");
        tableModel.addColumn("账号");
        tableModel.addColumn("税号");
        tableModel.addColumn("联系人");

        customerTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(customerTable);

        // 按钮面板
        JPanel buttonPanel = new JPanel();
        JButton addBtn = new JButton("添加");
        JButton editBtn = new JButton("修改");
        JButton deleteBtn = new JButton("删除");
        JButton refreshBtn = new JButton("刷新");

        buttonPanel.add(addBtn);
        buttonPanel.add(editBtn);
        buttonPanel.add(deleteBtn);
        buttonPanel.add(refreshBtn);

        setLayout(new BorderLayout());
        add(scrollPane, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        loadCustomerData();

        // 事件监听
        addBtn.addActionListener(e -> {
            new CustomerEditDialog(null).setVisible(true);
            loadCustomerData();
        });

        editBtn.addActionListener(e -> {
            int selectedRow = customerTable.getSelectedRow();
            if (selectedRow >= 0) {
                String cno = (String) tableModel.getValueAt(selectedRow, 0);
                new CustomerEditDialog(cno).setVisible(true);
                loadCustomerData();
            } else {
                JOptionPane.showMessageDialog(this, "请选择要修改的行", "提示", JOptionPane.WARNING_MESSAGE);
            }
        });

        deleteBtn.addActionListener(e -> deleteCustomer());
        refreshBtn.addActionListener(e -> loadCustomerData());
    }

    private void loadCustomerData() {
        tableModel.setRowCount(0);

        try (Connection conn = DBUtil.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT * FROM customer")) {

            while (rs.next()) {
                tableModel.addRow(new Object[]{
                        rs.getString("cno"),
                        rs.getString("cname"),
                        rs.getString("caddress"),
                        rs.getString("czhang"),
                        rs.getString("cshui"),
                        rs.getString("cpeople")
                });
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载数据失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void deleteCustomer() {
        int selectedRow = customerTable.getSelectedRow();
        if (selectedRow >= 0) {
            String cno = (String) tableModel.getValueAt(selectedRow, 0);

            int confirm = JOptionPane.showConfirmDialog(
                    this,
                    "确定要删除客户 " + cno + " 吗?",
                    "确认删除",
                    JOptionPane.YES_NO_OPTION);

            if (confirm == JOptionPane.YES_OPTION) {
                try (Connection conn = DBUtil.getConnection();
                     PreparedStatement pstmt = conn.prepareStatement("DELETE FROM customer WHERE cno = ?")) {

                    pstmt.setString(1, cno);
                    int affectedRows = pstmt.executeUpdate();

                    if (affectedRows > 0) {
                        JOptionPane.showMessageDialog(this, "删除成功");
                        loadCustomerData();
                    }
                } catch (SQLException e) {
                    JOptionPane.showMessageDialog(this, "删除失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, "请选择要删除的行", "提示", JOptionPane.WARNING_MESSAGE);
        }
    }
}

class CustomerEditDialog extends JDialog {
    private JTextField cnoField, cnameField, caddressField, czhangField, cshuiField, cpeopleField;
    private boolean isEditMode;

    public CustomerEditDialog(String cno) {
        if (cno == null) {
            setTitle("添加客户");
            isEditMode = false;
        } else {
            setTitle("修改客户");
            isEditMode = true;
        }

        setSize(500, 350);
        setModal(true);
        setLocationRelativeTo(null);

        JPanel panel = new JPanel(new GridLayout(6, 2, 5, 5));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        panel.add(new JLabel("客户编号:"));
        cnoField = new JTextField();
        if (isEditMode) cnoField.setEditable(false);
        panel.add(cnoField);

        panel.add(new JLabel("客户名称:"));
        cnameField = new JTextField();
        panel.add(cnameField);

        panel.add(new JLabel("客户地址:"));
        caddressField = new JTextField();
        panel.add(caddressField);

        panel.add(new JLabel("客户账号:"));
        czhangField = new JTextField();
        panel.add(czhangField);

        panel.add(new JLabel("客户税号:"));
        cshuiField = new JTextField();
        panel.add(cshuiField);

        panel.add(new JLabel("联系人:"));
        cpeopleField = new JTextField();
        panel.add(cpeopleField);

        JButton saveBtn = new JButton("保存");
        saveBtn.addActionListener(e -> saveCustomer());

        JButton cancelBtn = new JButton("取消");
        cancelBtn.addActionListener(e -> dispose());

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
        buttonPanel.add(saveBtn);
        buttonPanel.add(cancelBtn);

        add(panel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        if (isEditMode) {
            loadCustomerData(cno);
        }
    }

    private void loadCustomerData(String cno) {
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM customer WHERE cno = ?")) {

            pstmt.setString(1, cno);
            ResultSet rs = pstmt.executeQuery();

            if (rs.next()) {
                cnoField.setText(rs.getString("cno"));
                cnameField.setText(rs.getString("cname"));
                caddressField.setText(rs.getString("caddress"));
                czhangField.setText(rs.getString("czhang"));
                cshuiField.setText(rs.getString("cshui"));
                cpeopleField.setText(rs.getString("cpeople"));
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载数据失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void saveCustomer() {
        String cno = cnoField.getText().trim();
        String cname = cnameField.getText().trim();
        String caddress = caddressField.getText().trim();
        String czhang = czhangField.getText().trim();
        String cshui = cshuiField.getText().trim();
        String cpeople = cpeopleField.getText().trim();

        // 验证输入
        if (cno.isEmpty() || cname.isEmpty()) {
            JOptionPane.showMessageDialog(this, "客户编号和名称不能为空", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        try (Connection conn = DBUtil.getConnection()) {
            PreparedStatement pstmt;

            if (isEditMode) {
                pstmt = conn.prepareStatement(
                        "UPDATE customer SET cname=?, caddress=?, czhang=?, cshui=?, cpeople=? WHERE cno=?");
                pstmt.setString(1, cname);
                pstmt.setString(2, caddress);
                pstmt.setString(3, czhang);
                pstmt.setString(4, cshui);
                pstmt.setString(5, cpeople);
                pstmt.setString(6, cno);
            } else {
                pstmt = conn.prepareStatement(
                        "INSERT INTO customer (cno, cname, caddress, czhang, cshui, cpeople) VALUES (?, ?, ?, ?, ?, ?)");
                pstmt.setString(1, cno);
                pstmt.setString(2, cname);
                pstmt.setString(3, caddress);
                pstmt.setString(4, czhang);
                pstmt.setString(5, cshui);
                pstmt.setString(6, cpeople);
            }

            int affectedRows = pstmt.executeUpdate();

            if (affectedRows > 0) {
                JOptionPane.showMessageDialog(this, "保存成功");
                dispose();
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "保存失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}